import { NextRequest, NextResponse } from "next/server";
import jose, { jwtVerify } from "jose";
import stringify from "json-stringify-safe";
import { omit } from "@/utils/_";

export async function middleware(request: NextRequest) {
  const { cookies } = request;
  const authorization = cookies.get("Authorization");
  const secret = new TextEncoder().encode(process.env.JWT_SECRET);

  if (
    !request.url.includes("login") &&
    request.nextUrl.pathname.startsWith("/login")
  ) {
    return NextResponse.next();
  }

  if (!authorization?.value) {
    return NextResponse.redirect(`${request.nextUrl.origin}/login`);
  }

  try {
    const parsed = await jwtVerify(authorization?.value, secret);
    if (parsed) {
      const response = NextResponse.next();
      response.cookies.set({
        name: "user",
        value: encodeURIComponent(
          stringify(omit(parsed.payload, ["salt", "password"])),
        ),
        maxAge: 60 * 60 * 24,
      });
      return response;
    }
  } catch (e) {
    NextResponse.redirect(`${request.nextUrl.origin}/login`);
  }
}

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|api/login|api/register|login|custom-font.woff2).*)",
  ],
  unstable_allowDynamic: ["/node_modules/lodash"],
};
